package com.authine.cloudpivot.ext.service.impl;

import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.transfer.ExportVendorPayAbleDto;
import com.authine.cloudpivot.ext.service.ExportReportService;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.kingdee.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: liwei
 * @DateTime: 2021/9/23
 * @Description: TODO
 */
@Slf4j
public class ExportReportServiceImpl implements ExportReportService {
    @Override
    public List<Map<String, Object>> vendorAccountPayableReport(ExportVendorPayAbleDto vParam) {

        if (null == vParam) {
            return null;
        }

        String invoiceItemize = JdbcTemplateUtils.getTableName(ModelConst.T_INVOICE_ITEMIZE);//采购收票流水
        String memberPurchaseOrder = JdbcTemplateUtils.getTableName(ModelConst.T_MEMBER_PURCHASE_ORDER); //会员采购订单表
        String purchaseRequestPaymentDetail = JdbcTemplateUtils.getTableName(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL); //采购付款明细
        String transferVendor = JdbcTemplateUtils.getTableName(ModelConst.T_TRANSFER_VENDOR); //转采供应商

        List<String> predicateOrInvoiceTime = new ArrayList<>();
        List<String> predicateOrPayment = new ArrayList<>();

        //todo , c.invoice_time AS invoiceTime
        StringBuilder sqlBd = new StringBuilder(" SELECT o.po_code AS poCode, DATE_FORMAT( o.createdTime, '%Y-%m-%d' ) AS purchaseTime, o.purchase_amount AS purchaseAmount, v.company_name AS vendorName, b.payment AS payment, b.payment_time AS paymentTime, C.invoice_amount AS invoiceAmount, C.invoice_time AS invoiceTime, o.platform_name as platformName FROM ");
        sqlBd.append(memberPurchaseOrder);
        sqlBd.append(" AS o LEFT JOIN ");
        sqlBd.append(transferVendor);
        sqlBd.append(" AS v ON v.ID = o.vendor_id ");

        //统计付款总和
        StringBuilder paymentSqlBd = new StringBuilder(" LEFT JOIN ( SELECT d.member_purchase_order_id, SUM(d.payment) AS payment, GROUP_CONCAT( DISTINCT DATE_FORMAT( d.financial_confirm_time, '%Y-%m-%d' )) AS payment_time FROM ");
        paymentSqlBd.append(purchaseRequestPaymentDetail);
        paymentSqlBd.append(" AS d  WHERE  d.deleted = FALSE   AND d.payment_detail_status = 3 ");

        StringBuilder paymentGroupBd = new StringBuilder(" GROUP BY  d.member_purchase_order_id ) AS b ON b.member_purchase_order_id = o.ID ");

        //统计发票总和  %Y-%m-%d %H:%i:%S
        StringBuilder invoiceSqlBd = new StringBuilder(" LEFT JOIN ( SELECT purchase_id,GROUP_CONCAT( DISTINCT DATE_FORMAT( financial_confirmation_time, '%Y-%m-%d')) AS invoice_time,SUM(invoice_amount) AS invoice_amount FROM ");
        invoiceSqlBd.append(invoiceItemize);
        invoiceSqlBd.append(" WHERE deleted = FALSE AND invoice_itemize_status = 4 ");

        StringBuilder invoiceGroupBd = new StringBuilder(" GROUP BY purchase_id ) AS C ON C.purchase_id = o.ID ");

        StringBuilder whereBd = new StringBuilder(" WHERE o.deleted = FALSE  AND o.member_purchase_order_status NOT IN (1,5,6,7) ");

        if (null != vParam.getVendorName() && !vParam.getVendorName().trim().equals("")) {
            whereBd.append( " and upper(v.company_name) like '%");
            whereBd.append(vParam.getVendorName().trim().toUpperCase());
            whereBd.append("%' ");
        }

        if (null != vParam.getPoCode() && !vParam.getPoCode().trim().equals("")) {
            whereBd.append( " and upper(o.po_code) like '%");
            whereBd.append(vParam.getPoCode().trim().toUpperCase());
            whereBd.append("%' ");
        }
        if (null != vParam.getPlatformName() && !vParam.getPlatformName().trim().equals("")) {
            whereBd.append(" and o.platform_name like '%");
            whereBd.append(vParam.getPlatformName().trim());
            whereBd.append("%' ");
        }
        if (null != vParam.getPaymentTimeStart()) {
            String paymentStartStr = DateUtils.dateToStr(vParam.getPaymentTimeStart(), DateUtils.FORMAT_PATTERN_DATETIME);
            predicateOrPayment.add(" d.financial_confirm_time >= '" + paymentStartStr + "' ");
        }
        if (null != vParam.getPaymentTimeEnd()) {
            String paymentEndStr = DateUtils.dateToStr(vParam.getPaymentTimeEnd(), DateUtils.FORMAT_PATTERN_DATETIME);
            predicateOrPayment.add(" d.financial_confirm_time <= '" + paymentEndStr + "' ");

        }

        if (null != vParam.getInvoiceTimeStart()) {
            String invoiceStartStr = DateUtils.dateToStr(vParam.getInvoiceTimeStart(), DateUtils.FORMAT_PATTERN_DATETIME);
            predicateOrInvoiceTime.add("financial_confirmation_time >= '" + invoiceStartStr + "' ");

        }

        if (null != vParam.getInvoiceTimeEnd()) {
            String invoiceEndStr = DateUtils.dateToStr(vParam.getInvoiceTimeEnd(), DateUtils.FORMAT_PATTERN_DATETIME);
            predicateOrInvoiceTime.add("financial_confirmation_time <= '" + invoiceEndStr + "' ");
        }
        if (!predicateOrInvoiceTime.isEmpty() && !predicateOrPayment.isEmpty()) {
            String invoiceTimeOrStr = predicateOrInvoiceTime.size() == 1 ? predicateOrInvoiceTime.get(0) : StringUtils.join(predicateOrInvoiceTime, " and ");
            String paymentOrStr = predicateOrPayment.size() == 1 ? predicateOrPayment.get(0) : StringUtils.join(predicateOrPayment, " and ");
            paymentSqlBd.append(" and  ");
            paymentSqlBd.append(paymentOrStr);
            paymentSqlBd.append(" ");
            invoiceSqlBd.append(" and ");
            invoiceSqlBd.append(invoiceTimeOrStr);
            invoiceSqlBd.append(" ");
            if (null != vParam.getIsOrAnd()) {
                //判断或 逻辑 默认是并且
                if (vParam.getIsOrAnd()) {
                    whereBd.append(" and c.invoice_time is not null or  b.payment_time is not  null");

                } else {
                    whereBd.append(" and c.invoice_time is not null and  b.payment_time is not  null");
                }
            }

        } else if (!predicateOrInvoiceTime.isEmpty()) {
            String invoiceTimeOrStr = predicateOrInvoiceTime.size() == 1 ? predicateOrInvoiceTime.get(0) : StringUtils.join(predicateOrInvoiceTime, " and ");
            invoiceSqlBd.append(" and  ");
            invoiceSqlBd.append(invoiceTimeOrStr);
            whereBd.append(" and c.invoice_time is not null ");
        } else if (!predicateOrPayment.isEmpty()) {
            String paymentOrStr = predicateOrPayment.size() == 1 ? predicateOrPayment.get(0) : StringUtils.join(predicateOrPayment, " and ");
            paymentSqlBd.append(" and  ");
            paymentSqlBd.append(paymentOrStr);
            whereBd.append("   and  b.payment_time is not  null ");

        }
        sqlBd.append(paymentSqlBd);
        sqlBd.append(paymentGroupBd);
        sqlBd.append(invoiceSqlBd);
        sqlBd.append(invoiceGroupBd);
        sqlBd.append(whereBd);
        log.info("vendorAccountPayableReport sql:{}",sqlBd);

        List<Map<String, Object>> mapList = JdbcTemplateUtils.queryForList(sqlBd.toString(), null);

        log.info("vendorAccountPayableReport query result:{}",mapList);

        return mapList;
    }




}
